#include "YGFileStreamWM6.h"

#include "YGFileManager.h"

namespace YoghurtGum
{

	


	FileStreamWM6::FileStreamWM6()
	{

	}

	FileStreamWM6::~FileStreamWM6()
	{

	}

	bool FileStreamWM6::Open(const char* a_File, uint32 a_Options)
	{
		uint32 length = (uint32)(FileManager::Get().GetWorkingDirectoryLength() + strlen(a_File));
		m_FilePath = new char[length + 1];
		strcpy(m_FilePath, FileManager::Get().GetWorkingDirectory());
		strcat(m_FilePath, a_File);

		char options[8] = { 0 };

		if (a_Options & YG_FILE_READ) { strcpy(options, "r"); }
		if (a_Options & YG_FILE_WRITE) 
		{ 
			if (a_Options & YG_FILE_CLEAR)
			{
				strcpy(options, "w+"); 
			}
			else
			{
				strcpy(options, "a"); 
			}
		}

		m_Handle = fopen(m_FilePath, options);
		
		if (!m_Handle)
		{
			ERROR_EXPLAIN("Could not open '%s'.", a_File);
			return false;
		}

		return false;
	}

	bool FileStreamWM6::Read(void* a_Dst, uint32 a_ElementSize, uint32 a_Count /*= 1*/)
	{
		size_t result = fread(a_Dst, a_ElementSize, a_Count, m_Handle);
		return (result == a_Count * a_ElementSize);
	}

	bool FileStreamWM6::ReadUint8(uint8* a_Dst, uint32 a_Count /*= 1*/)
	{
		size_t result = fread(a_Dst, 1, a_Count, m_Handle);
		return (result == a_Count);
	}

	bool FileStreamWM6::ReadUint16(uint16* a_Dst, uint32 a_Count /*= 1*/)
	{
		size_t result = fread(a_Dst, 2, a_Count, m_Handle);
		return (result == a_Count * 2);
	}

	bool FileStreamWM6::ReadUint32(uint32* a_Dst, uint32 a_Count /*= 1*/)
	{
		size_t result = fread(a_Dst, 4, a_Count, m_Handle);
		return (result == a_Count * 4);
	}

	bool FileStreamWM6::Seek(uint32 a_Offset, uint32 a_Options)
	{
		if (a_Options & YG_SEEK_START) 
		{ 
			fseek(m_Handle, a_Offset, SEEK_SET); 
		}
		else if (a_Options & YG_SEEK_CURR) 
		{ 
			fseek(m_Handle, a_Offset, SEEK_CUR); 
		}
		else if (a_Options & YG_SEEK_END) 
		{ 
			fseek(m_Handle, a_Offset, SEEK_END);
		}

		return true;
	}

	bool FileStreamWM6::EndOfFile()
	{
		return false;
	}

	bool FileStreamWM6::Close()
	{
		if (m_Handle)
		{
			fclose(m_Handle);
			return true;
		}

		return false;
	}

}